package com.zsd.android.recyclerviewlibrary.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import com.zsd.android.recyclerviewlibrary.holder.RViewHolder;
import com.zsd.android.recyclerviewlibrary.listener.RViewItem;
import com.zsd.android.recyclerviewlibrary.manager.RViewItemManager;

import java.util.ArrayList;

public class RViewAdapter<T> extends RecyclerView.Adapter<RViewHolder> {

    private ArrayList<T> list;
    private RViewItemManager<T> itemManager;
    protected int headCount, footCount;

    public RViewAdapter(ArrayList<T> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        this.list = list;
        itemManager = new RViewItemManager<>();
    }

    public RViewAdapter(ArrayList<T> list, RViewItem<T> item) {
        this(list);
        addItem(item);
    }

    public void addItem(RViewItem<T> item) {
        itemManager.addItem(item);
    }

    @NonNull
    @Override
    public RViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        RViewItem<T> item = itemManager.getItem(viewType);
        RViewHolder holder = RViewHolder.create(viewGroup.getContext(), viewGroup, item.getItemLayout());
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RViewHolder holder, int position) {
        itemManager.convertView(holder, list.get(position), holder.getAdapterPosition());
    }

    @Override
    public int getItemCount() {
        return (list != null ? list.size() : 0) + headCount + footCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (hasMultiStyle()) {
            return itemManager.getItemStyle(list.get(position), position);
        }
        return super.getItemViewType(position);
    }

    private boolean hasMultiStyle() {
        return itemManager.getItemStyleCount() > 0;
    }

    public int getHeadCount() {
        return headCount;
    }

    public void setHeadCount(int headCount) {
        this.headCount = headCount;
    }

    public int getFootCount() {
        return footCount;
    }

    public void setFootCount(int footCount) {
        this.footCount = footCount;
    }

}
